<template>
  <div class="users-manage">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
    </div>

    <el-table :data="users" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'info'">
            {{ row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'warning'">
            {{ row.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              :disabled="row.role === 'admin'"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="form.id ? '编辑用户' : '添加用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'UsersManage',
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    const users = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const formRef = ref(null)

    const form = ref({
      id: '',
      username: '',
      email: '',
      phone: '',
      password: '',
      role: 'user',
      status: 'active'
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    const fetchUsers = async () => {
      loading.value = true
      try {
        const response = await axios.get('http://localhost:3000/users')
        users.value = response.data
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleEdit = (row) => {
      form.value = { ...row }
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      if (row.role === 'admin') {
        ElMessage.warning('不能删除管理员账号')
        return
      }

      ElMessageBox.confirm(
        '确定要删除该用户吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await axios.delete(`http://localhost:3000/users/${row.id}`)
          ElMessage.success('删除成功')
          fetchUsers()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        
        if (form.value.id) {
          // 编辑用户时，获取原始用户数据
          const originalUserResponse = await axios.get(`http://localhost:3000/users/${form.value.id}`)
          const originalUser = originalUserResponse.data
          
          // 保持原始密码不变
          const updateData = {
            ...form.value,
            password: originalUser.password // 使用原始密码
          }
          
          await axios.put(`http://localhost:3000/users/${form.value.id}`, updateData)
          ElMessage.success('更新成功')
        } else {
          // 添加新用户时，生成新的ID
          const usersResponse = await axios.get('http://localhost:3000/users')
          const users = usersResponse.data
          
          // 找到当前最大的ID
          const maxId = users.reduce((max, user) => {
            const userId = parseInt(user.id)
            return isNaN(userId) ? max : Math.max(max, userId)
          }, 0)
          
          // 新用户的ID为最大ID + 1
          const newUserData = {
            ...form.value,
            id: (maxId + 1).toString() // 确保ID是字符串类型
          }
          
          await axios.post('http://localhost:3000/users', newUserData)
          ElMessage.success('添加成功')
        }
        
        dialogVisible.value = false
        fetchUsers()
        formRef.value.resetFields()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }

    onMounted(() => {
      console.log('用户管理页面加载')
      fetchUsers()
    })

    return {
      users,
      loading,
      dialogVisible,
      form,
      formRef,
      rules,
      handleEdit,
      handleDelete,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.users-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: black;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style> 